﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Linq.Expressions;

namespace LibraryMusicStore.DAL
{
    public class Repository<T> : IRepository<T> where T : class
    {
        public MusicStoreEntities Context { get; set; }

        public Repository()
        {
            Context = new MusicStoreEntities();
        }
    
        public virtual T GetById(int id)
        {
            var itemParameter = Expression.Parameter(typeof(T), "item");
            var whereExpression = Expression.Lambda<Func<T, bool>>
                (
                Expression.Equal(
                    Expression.Property(
                        itemParameter,
                        GetPrimaryKeyName<T>()
                        ),
                    Expression.Constant(id)
                    ),
                new[] { itemParameter }
                );
            var table = Context.GetTable<T>();
            return table.Where(whereExpression).Single();
        }

        public string GetPrimaryKeyName<T>()
        {
            var type = Context.Mapping.GetMetaType(typeof(T));

            var PK = (from m in type.DataMembers
                      where m.IsPrimaryKey
                      select m).Single();
            return PK.Name;
        }

        public virtual IQueryable<T> GetAll()
        {
            return Context.GetTable<T>();
        }

        public virtual void InsertOnSubmit(T entity)
        {
            GetTable().InsertOnSubmit(entity);
        }

        public virtual void DeleteOnSubmit(T entity)
        {
            GetTable().DeleteOnSubmit(entity);
        }

        public virtual void SubmitChanges()
        {
            Context.SubmitChanges();
        }

        public virtual ITable GetTable()
        {
            return Context.GetTable<T>();
        }
    }
}
